package com.ceba.test.base.utils;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ceba.base.helper.LoggerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import abc.util.FileHelper;
import abc.util.StringUtils;

@SuppressWarnings("deprecation")
public class StringUtil {
	
	static Logger logger = LoggerFactory.getLogger(StringUtil.class);
	/**
	 * 判断是否为空串
	 * @param value
	 * @return
	 */
	public static Boolean isEmptyString(String value){
		if(value == null || "".equals(value)){
			return true;
		}else{
			return value.length() == 0?true:false;
		}
		
			
	}
	
	/**
	 * 去掉空格
	 * @param value
	 * @return
	 */
	public static String removeBlank(String value){
		if(!isEmptyString(value)){
			value = value.trim();
			value = value.replaceAll(" ","");
		}
		return value;
	}
	
	/**
	 * 替换所有包括制表符的空格
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
	
	/**
	 * 是否是数字
	 * @param str
	 * @return
	 */
	public static boolean isNum(String str){
		if(str.equals("") || str==null) return false;
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}
	
	/**
	 * 将字节转成kb
	 * @param sizeS
	 * @return
	 */
	public static BigDecimal stringTOkb(String sizeS){
		BigDecimal size = new BigDecimal(0);
		if(!isEmptyString(sizeS)){
			size = new BigDecimal(sizeS);
			size = size.divide(new BigDecimal(1024), 1, BigDecimal.ROUND_HALF_EVEN);
		}
		return size;
	}
	
	public static String decode(String urlString){

		if(StringUtils.isNotNullAndEmpty(urlString)){
			try {
				urlString=URLDecoder.decode(urlString,"UTF-8");
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
			}
		}
		return urlString;
	}
	
	/**
	 * 给路径添加斜杠
	 * 如:e:/ceba  ---> e:/ceba/
	 * @param path
	 * @return
	 */
	public static String addLastSlash(String path){
		if(!isEmptyString(path)){
			path = path.trim();
			int pos = path.lastIndexOf("/");
			if(pos != path.length() - 1){
				path = path + "/";
			}
		}
		return path;
	}
	/**
	 * 删除路径开头斜杠
	 * 如:/ceba  ---> ceba/
	 * @param path
	 * @return
	 */
	public static String deleteFirstSlash(String path){
		if(!isEmptyString(path) && path.length()>2){
			path = path.trim();
			int pos = path.indexOf("/");
			if(pos == 0){
				path = path.substring(1, path.length());
			}
		}
		return path;
	}
	public static String deleteLastSlash(String path){
		if(!isEmptyString(path)){
			path = path.trim();
			int pos = path.lastIndexOf("/");
			if(pos == path.length() - 1){
				path = path.substring(0, pos);
			}
		}
		return path;
	}
	
	public static void main(String[]args) throws IOException{
		String path = "E:/接口测试/2";
		if(!new File(path).isDirectory()){
			new File(path).mkdirs();
		}
		System.out.println(FileHelper.exists(path));
	}
	
	public static boolean isIpv4(String ipAddress) {

		String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
			    +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
			    +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
			    +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

		Pattern pattern = Pattern.compile(ip);
		Matcher matcher = pattern.matcher(ipAddress);
		return matcher.matches();

	}
	
	private static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}
	
	public static boolean isMessyCode(String strName) {
		Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
		Matcher m = p.matcher(strName);
		String after = m.replaceAll("");
		String temp = after.replaceAll("\\p{P}", "");
		char[] ch = temp.trim().toCharArray();
		float chLength = 0 ;
		float count = 0;
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (!Character.isLetterOrDigit(c)) {
				if (!isChinese(c)) {
					count = count + 1;
				}
				chLength++; 
			}
		}
		float result = count / chLength ;
		if (result > 0.4) {
			return true;
		} else {
			return false;
		}
	}
	
	
	public static String toChinese(String msg){
		if(isMessyCode(msg)){
			try {
				return new String(msg.getBytes("ISO8859-1"), "UTF-8");
			} catch (Exception e) {
			}
		}
		return msg ; 
	}
	
	/**
	 * 判断内容的后缀是否存在于字符串中
	 * @param endsWith
	 * @param content
	 * @return
	 */
	public static boolean isEndsWith(String endsWith,String content){
		String[] endsWiths=endsWith.split(",");
		for(int i=0;i<endsWiths.length;i++){
			if(content.endsWith(endsWiths[i])){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 多个id之间通过
	 * @param stampIds
	 * @param prefix  字符串之间分割的符号
	 * @return
	 */
	public static List<String> getListStringsByPrefix(String ids,String prefix){
		List<String> list = new ArrayList<String> ();
		if(!StringUtil.isEmptyString(ids)){
			String[] others = ids.split(prefix);
			if(others !=null && others.length >0){
				for(String oS:others){
					if(!StringUtil.isEmptyString(oS)){
						list.add(oS);
					}
				}
			}
		}
		return list;
	}
	
	//过滤关键字中首尾特殊符号
	public static String filterSpecilKeyWordPrefixSuffix(String str,String express){
		Pattern pattern = Pattern.compile("^["+express+"]*+|["+express+"]*+$");
        Matcher matcher = pattern.matcher(str);
        return matcher.replaceAll("");
	}
	
	
  //过滤文件名字中的特殊符号
	public static String indexRepxStr(String str, String repx) {
		Pattern pattern = Pattern.compile(repx);
		Matcher matcher = pattern.matcher(str);
		StringBuffer buffer = new StringBuffer();
		while (matcher.find()) {
			buffer.append(str.substring(matcher.start(), matcher.end()));
		}
		return buffer.toString();
	}
	
	/**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isSpecialChar(String str,String express) {
        Pattern p = Pattern.compile(express);
        Matcher m = p.matcher(str);
        return m.find();
    }
    
	/** 
	 * 判断查询参数中是否以特殊字符开头，如果以特殊字符开头则返回true，否则返回false 
	 *  
	 * @param value 
	 * @return 
	 * @see {@link #getQueryRegex()} 
	 * @see {@link #DEFAULT_QUERY_REGEX} 
	 */  
	public boolean specialSymbols(String value,String express) {  
	    if (StringUtil.isEmptyString(value)) {  
	        return false;  
	    }  
	    Pattern pattern = Pattern.compile(express);  
	    Matcher matcher = pattern.matcher(value);  

	    char[] specialSymbols = express.toCharArray();  

	    boolean isStartWithSpecialSymbol = false; // 是否以特殊字符开头  
	    for (int i = 0; i < specialSymbols.length; i++) {  
	        char c = specialSymbols[i];  
	        if (value.indexOf(c) == 0) {  
	            isStartWithSpecialSymbol = true;  
	            break;  
	        }  
	    }  

	    return matcher.find() && isStartWithSpecialSymbol;  
	}

	/**
	 * 判断字符串是否正整数
	 * @param str
	 * @return
	 */
	public static boolean isPositiveInteger(String str) {
		return str.matches("\\d+");
	}


}
